const path = require("path");
const puppeteer = require("puppeteer");
const { pdfDir, pdfDirMonth } = require("../config");

const env = process.env.NODE_ENV || "development";

console.log(`当前执行环境：${env}\n`);

const urlPreFix =
  env === "development"
    ? "http://report.bjsdzk.com"
    : "http://192.168.1.231:81";

// args: ['--no-sandbox', '--disable-setuid-sandbox']
async function buildPdf({ token, deviceId, name, companyId, uuid }) {
  const browser = await puppeteer.launch();
  try {
    const url = `${urlPreFix}/pc/weekly/106/${companyId}/${deviceId}/${token}`;
    const filename = path.resolve(pdfDir, uuid + "/", name + ".pdf");
    const page = await browser.newPage();
    await page.goto(url, {
      timeout: 0,
      waitUntil: "load"
    });
    await page.waitFor(3000);
    await page.pdf({
      path: filename,
      format: "A4"
    });
    console.log("文件名称：" + filename);
    await browser.close();
  } catch (error) {
    await browser.close();
    console.log("===========打开页面出错==============");
    console.error(error);
    console.log("====================================");
    return Promise.reject(new Error(error));
  }
}

async function buildPdfMonth({ token, name, companyId, uuid }) {
  const browser = await puppeteer.launch();
  try {
    // /pc/monthly/106/:companyId/:token/:download/:platform?
    const url = `${urlPreFix}/pc/monthly/106/${companyId}/${token}/false`;
    const filename = path.resolve(pdfDirMonth, uuid + "/", name + ".pdf");
    const page = await browser.newPage();
    await page.goto(url, {
      timeout: 0,
      waitUntil: "load"
    });
    await page.waitFor(3000);
    await page.screenshot({
      fullPage: true,
      path: "image.png"
    });
    await page.pdf({
      path: filename,
      format: "A4"
    });
    console.log("文件名称：" + filename);
    await browser.close();
  } catch (error) {
    await browser.close();
    console.log("===========打开页面出错==============");
    console.error(error);
    console.log("====================================");
    return Promise.reject(new Error(error));
  }
}

async function gzipFolder() {}

module.exports = {
  buildPdf,
  buildPdfMonth
};
